<?php

namespace app\api\server\music;

use app\api\model\music\MusicCommentApiModel;
use app\api\model\music\MusicApiModel;
use app\admin\ServerBase;
use app\api\model\music\MusicTypeApiModel;
use app\api\model\order\OrderMusicApiModel;
use app\api\model\user\UserGoodsApiModel;
use app\api\model\UserModel;
use app\logic\single\GoodsSingle;
use think\facade\Db;
use think\Request;
use think\db\Expression;

class MusicServer extends ServerBase
{
    protected $model;
    protected $request;
    protected $default_field = 'id,title,user_id,url,img,price,original_price,play_num,sale';
    /**
     * @var mixed
     */
    protected $param;
    /**
     * @var mixed
     */
    protected $validate;
    /**
     * @var MusicCommentApiModel
     */
    private $goodsCommentModel;
    /**
     * @var OrderMusicApiModel
     */
    private $OrderMusicModel;
    /**
     * @var MusicTypeApiModel
     */
    private $typeModel;

    function __construct( Request $request)
    {
        $this->request=$request;
        $this->param=$request->param();
        $this->model=new MusicApiModel();
        $this->goodsCommentModel = new MusicCommentApiModel();
        $this->OrderMusicModel = new OrderMusicApiModel();
        $this->typeModel = new MusicTypeApiModel();
    }
    function getType(){
        $list = $this->typeModel->where('status',1)->field('id,title')
            ->order('sort desc,id desc')->select();
        $this->getMessageCode('adminMessage.success.select',2);
        return $list;
    }
    function getList(){
        [$page,$limit] = $this->getPage($this->param);
        $this->param['single_status']=1;
        [$list,$count] = $this->model->getApiList($this->param,[],$this->default_field,$page,$limit);
        $result['data']=$list;
        $result['count']=$count;
        $this->getMessageCode('adminMessage.success.select',2);
        return $result;
    }

    function getDetail(){
        $info = $this->model->details($this->request->param('id'),$this->default_field.',content,type_id');
        $info['is_have'] = GoodsSingle::getInstance()->isHave($info['id'],10,$this->request->user_id);
        $this->getMessageCode('adminMessage.success.select',2);
        return $info;
    }
    function get_comment_list(){
        [$page,$limit] = $this->getPage($this->param);
        $goods_id = $this->param['goods_id']??0;
        $type = $this->param['type']??0;
        if(empty($goods_id) || empty($type) ){
            $this->getMessageCode('code_common.illegal',1);
            return false;
        }
        [$list,$count] = $this->goodsCommentModel->getApiList($goods_id,$type,$page,$limit);
        $result['data']=$list;
        $result['count']=$count;
        $this->getMessageCode('adminMessage.success.select',2);
        return $result;
    }
    function create_comment(){
        $goods_id = $this->param['goods_id']??0;
        $type = $this->param['type']??0;
        $order_id = $this->param['order_id']??0;
        if(empty($goods_id) || empty($type) ){
            $this->getMessageCode('code_common.illegal',1);
            return false;
        }
        $content = $this->request->post('content');
        if(empty($content)){
            $this->ERROR='请输入内容';
            return false;
        }
        if(!empty($order_id)){
            $order = $this->OrderMusicModel->getFindByUserIdAndId($order_id,$this->request->user_id);
            if(empty($order)){
                $this->ERROR='订单不存在';
                return false;
            }
            if($order['status'] <= 10){
                $this->ERROR='订单不能评论';
                return false;
            }
        }
        Db::startTrans();
        try{
            $this->goodsCommentModel->create_comment($this->request->user_id,$goods_id,$type,$content);
            if(!empty($order)){
                $this->OrderMusicModel->where('id',$order_id)->save(['status'=>30]);
            }
            Db::commit();
        }catch (\Exception $exception){
            Db::rollback();
            $this->ERROR=$exception->getMessage();
            return false;
        }
    }

    function getMusicByHistory(){
        $ids = $this->request->param('ids')??[];
        $ids_str = implode(',',$ids);
        $order= 'field(id, '.$ids_str.')';
        [$page,$limit] = $this->getPage($this->param);
        $list = Db::name('music')
            ->whereIn('id',$ids)
            ->where('single_status',1)
            ->order(Db::raw($order))
            ->page($page,$limit)
            ->column('id,user_id,title,url,img,play_num,sale','id');
        $arr =[];
        foreach ($ids as $key=>$val){
            $now_music = $list[$val] ?? [];
            if(!empty($now_music)){
                $arr[$key]=$now_music;
                $arr[$key]['is_have']=UserGoodsApiModel::isHave($val,10,$this->request->user_id);
                $arr[$key]['writer'] = UserModel::getInfoById($now_music['user_id'],'writer_name,writer_head_img');
            }else{
                $arr[$key]=['title'=>'已下架'];
            }
        }
        $result['data']=$arr;
        $result['count']=count($ids);
        $this->getMessageCode('adminMessage.success.select',2);
        return $result;
    }

    function musicPlay(){
        $goods_id = $this->param['goods_id']??0;
        $type = $this->param['type']??0;
        $music_id = $this->param['music_id']??0;
        if(empty($goods_id) || empty($type) || empty($music_id)){
            $this->getMessageCode('code_common.illegal',1);
            return false;
        }
        $res = GoodsSingle::getInstance()->IncPlayNum($goods_id,$type,$music_id);
        if($res === true){
            return true;
        }else{
            $this->ERROR=$res;
            return false;
        }
    }

    function getPan(){
        $type = $this->param['type']??0;
        $goods_id = $this->param['goods_id']??0;
        if(!in_array($type,[40,50]) || empty($goods_id)){
            $this->getMessageCode('code_common.illegal',1);
            return false;
        }
        //查询用户是否拥有该商品
        $res = GoodsSingle::getInstance()->isHave($goods_id,$type,$this->request->user_id);
        if(!$res){
            $this->getMessageCode('code_common.illegal',1);
            return false;
        }
        return GoodsSingle::getInstance()->getGoods($goods_id,$type,false,true);
    }
}